package com.iflytek.yly.jetpackdemo.livedata;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;

import com.iflytek.yly.jetpackdemo.R;

public class FragmentOne extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View parentView = inflater.inflate(R.layout.fragment_livedata_one, container, false);

        final SeekBar seekBar = parentView.findViewById(R.id.seekBar);

        // 注意：这里ViewModelProvider(getActivity())中的参数
        // 需要的是Activity,而不是Fragment,否则就收不到监听
        ShareDataViewModel shareDataViewModel = new ViewModelProvider(this.getActivity())
                .get(ShareDataViewModel.class);

        final MutableLiveData<Integer> liveData = (MutableLiveData<Integer>) shareDataViewModel.getProgress();
        // 通过 observe 方法观察ViewModel中字段数据的变化，并在变化时得到通知
        liveData.observe(this.getActivity(), new Observer<Integer>() {
            @Override
            public void onChanged(Integer progress) {
                seekBar.setProgress(progress);
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 当用户操作SeekBar时，更新ViewModel中的数据
                liveData.setValue(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        return parentView;
    }
}